package com.pinyoumei.app.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.AddressManagementAdapter;
import com.pinyoumei.app.bean.Address_List;
import com.pinyoumei.app.bean.UserAddressDeleteResponse;
import com.pinyoumei.app.bean.UserAddressListResponse;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.network.HttpMethods;
import com.pinyoumei.app.utils.DensityUtils;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.event.CouponFragmentEvent;
import com.pinyoumei.app.utils.event.PosFragmentEvent;
import com.pinyoumei.app.view.LoadingDailog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;


/**
 * 收货地址管理Activity
 */
public class AddressManagementActivity extends BaseActivity implements View.OnClickListener {
    private SwipeRecyclerView recyclerview;//滑动删除的RecycleView
    private AddressManagementAdapter adapter;
    private List<Address_List> list= new ArrayList<>();
    private RelativeLayout relative_finish;//返回
    private RelativeLayout relative_add;//加号 增加收货地址
    private int delete_position;//删除的数组下标
    private SmartRefreshLayout refreshLayout;
    private LoadingDailog loadingDailog;
    private String actiong = "";
    private String address_id = "";
    private rx.Subscriber subscriber;
    private rx.Subscriber subscriber1;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_addressmanagement);
        initwidget();
        actiong = getIntent().getAction();
        if(getIntent().hasExtra("id")){
            address_id = getIntent().getStringExtra("id");
        }
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        initRefresh();
        adapter = new AddressManagementAdapter(this,list);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickLisetner(new AddressManagementAdapter.OnItemClickListener(){
            @Override
            public void onClick(View view, int position){//这里是点击修改收货地址进入新增收货地址界面 需要将值传递过去
                switch (view.getId()){
                    case R.id.relative_click://点击整个item
                        if(TextUtils.isEmpty(actiong)){
                            return;
                        }
                        switch (actiong) {
                            case "ConfirmOrderActivity":
                                Intent intent = new Intent(AddressManagementActivity.this, ModificationAddressActivity.class);
                                intent.putExtra("id",list.get(position).getId());//地址的id
                                intent.putExtra("recieve_name",list.get(position).getRecieve_name());
                                intent.putExtra("recieve_phone",list.get(position).getRecieve_phone());
                                intent.putExtra("address_area",list.get(position).getAddress_area());
                                intent.putExtra("address_detail",list.get(position).getAddress_detail());
                                intent.putExtra("is_default",list.get(position).getIs_default());
                                intent.setAction("AddressManagementActivity");
                                setResult(2000,intent);
                                finish();
                                break;

                            case "CouponFragment":
                                EventBusUtils.postSticky(new CouponFragmentEvent(
                                        list.get(position).getId(),
                                        list.get(position).getRecieve_name(),
                                        list.get(position).getRecieve_phone(),
                                        list.get(position).getAddress_area(),
                                        list.get(position).getAddress_detail(),
                                        list.get(position).getIs_default()));
                                finish();
                                break;
                            case "PosFragment":
                                EventBusUtils.postSticky(new PosFragmentEvent(
                                        list.get(position).getId(),
                                        list.get(position).getRecieve_name(),
                                        list.get(position).getRecieve_phone(),
                                        list.get(position).getAddress_area(),
                                        list.get(position).getAddress_detail(),
                                        list.get(position).getIs_default()));
                                finish();
                                break;
                            default:
                                break;
                        }
                        break;
                    case R.id.image_change://点击修改按钮
                        Intent intent = new Intent(AddressManagementActivity.this,ModificationAddressActivity.class);
                        intent.putExtra("id",list.get(position).getId());//地址的id
                        intent.putExtra("recieve_name",list.get(position).getRecieve_name());
                        intent.putExtra("recieve_phone",list.get(position).getRecieve_phone());
                        intent.putExtra("address_area",list.get(position).getAddress_area());
                        intent.putExtra("address_detail",list.get(position).getAddress_detail());
                        intent.putExtra("is_default",list.get(position).getIs_default());
                        intent.setAction("AddressManagementActivity");
                        startActivity(intent);
                        break;
                }
            }
        });
        //请求收货地址管理列表
//        userAddressList(SPUtils.getAppUserId(this));
    }

    @Override
    protected void onResume(){
        super.onResume();
        //请求收货地址管理列表
        userAddressList(SPUtils.getAppUserId(this));
    }
    private void initwidget(){
        refreshLayout = findViewById(R.id.refreshLayout);
        relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);
        relative_add = findViewById(R.id.relative_add);
        relative_add.setOnClickListener(this);
        recyclerview = findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.addItemDecoration(new SpacesItemDecoration(DensityUtils.dip2px(AddressManagementActivity.this,10)));
        recyclerview.setSwipeMenuCreator(swipeMenuCreator);//设置滑动菜单
        recyclerview.setOnItemMenuClickListener(mMenuItemClickListener);//设置滑动菜单的点击监听
    }
    private void initRefresh(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener(){
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout){
                //请求收货地址管理列表
                userAddressList(SPUtils.getAppUserId(AddressManagementActivity.this));
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //请求收货地址管理列表
                userAddressList(SPUtils.getAppUserId(AddressManagementActivity.this));
            }
        });
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.relative_finish://返回
                finish();
                break;
            case R.id.relative_add://增加收货地址
                startActivity(new Intent(AddressManagementActivity.this,ModificationAddressActivity.class));
                break;
        }
    }
    //自定义一个ItemDecoration
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration{
        private int space;
        public SpacesItemDecoration(int space) {
            this.space = space;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state){
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            // Add top margin only for the first item to avoid double space between items
            if (parent.getChildPosition(view) == 0)
                outRect.top = DensityUtils.dip2px(AddressManagementActivity.this,15);
        }
    }
    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator(){
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            //int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            //int height = ViewGroup.LayoutParams.MATCH_PARENT;
            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(AddressManagementActivity.this)
                        .setBackgroundColor(Color.parseColor("#FF3A39"))
                        //.setImage(R.mipmap.delete_card)//删除卡片的背景图片
                        .setText("删除")
                        .setTextColor(Color.parseColor("#FFFFFF"))
                        .setWidth(200)
                        .setTextSize(15)
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
            }
        }
    };
    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = new OnItemMenuClickListener(){
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();
            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                //弹出是否删除信用卡Dialog
                //deleteCardDialog.show();
                delete_position = position;
                //用户收货地址删除
                userAddressDelete(SPUtils.getAppUserId(AddressManagementActivity.this),list.get(position).getId());
            }
        }
    };
    //请求收货地址管理列表
    private void userAddressList(String user_id){
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET));
        subscriber = new rx.Subscriber<UserAddressListResponse>() {
            @Override
            public void onStart(){
                super.onStart();
                loadingDailog.show();
            }
            @Override
            public void onCompleted(){

            }
            @Override
            public void onError(Throwable e){
                loadingDailog.dismiss();
                if(refreshLayout.getState().isHeader){
                    refreshLayout.finishRefresh();
                }else if(refreshLayout.getState().isFooter){
                    refreshLayout.finishLoadMore();
                }
            }
            @Override
            public void onNext(UserAddressListResponse userAddressListResponse){
                loadingDailog.dismiss();
                if(refreshLayout.getState().isHeader){
                    refreshLayout.finishRefresh();
                }else if(refreshLayout.getState().isFooter){
                    refreshLayout.finishLoadMore();
                }
                if(userAddressListResponse.getCode()>=0){
                    list.clear();
                    list.addAll(userAddressListResponse.getResult().getAddress_list());
                    adapter.notifyDataSetChanged();
                }
            }
        };
        HttpMethods.getInstance().userAddressList(subscriber,map);
    }
    //用户收货地址删除
    private void userAddressDelete(String user_id,String address_id){
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("address_id",address_id);
        map.put("sign",SignatureUtils.createSignature(map,Constants.SIGN_SECRET));
        subscriber1 = new Subscriber<UserAddressDeleteResponse>(){
            @Override
            public void onStart(){
                super.onStart();
                loadingDailog.show();
            }

            @Override
            public void onCompleted(){

            }

            @Override
            public void onError(Throwable e){
                loadingDailog.dismiss();
            }

            @Override
            public void onNext(UserAddressDeleteResponse userAddressDeleteResponse){
                loadingDailog.dismiss();
                if(userAddressDeleteResponse.getCode()>=0){
                    adapter.deleteData(delete_position);//删除源数据
                }
            }
        };
        HttpMethods.getInstance().userAddressDelete(subscriber1,map);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscriber!=null && !subscriber.isUnsubscribed()) {
            subscriber.unsubscribe();
        }

        if (subscriber1!=null && !subscriber1.isUnsubscribed()) {
            subscriber1.unsubscribe();
        }
    }
}
